package com.letv.core.utils;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.graphics.Rect;
import android.os.PowerManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.MeasureSpec;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;

import com.letv.android.sdk.R;
import com.letv.core.bean.TipMapBean.TipBean;
import com.letv.core.constant.LetvConstant;

/**
 * 与UI相关的工具类
 * 
 * @author zhuqiao
 * 
 */
public class UIsUtils {


    /**
     * 根据资源ID得到View
     */
    public static View inflate(Context context, int resource, ViewGroup root, boolean attachToRoot) {
        return LayoutInflater.from(context).inflate(resource, root, attachToRoot);
    }

    /**
     * 根据资源ID得到View
     */
    public static View inflate(Context context, int resource, ViewGroup root) {
        return LayoutInflater.from(context).inflate(resource, root);
    }

    /**
     * 得到屏幕宽度
     * 
     * @return
     */
//    public static int getScreenWidth() {
//        return ((WindowManager) BaseApplication.getInstance().getSystemService(Context.WINDOW_SERVICE))
//                .getDefaultDisplay().getWidth();
//    }

    public static int getScreenWidth(Context context) {
        return ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getWidth();
    }

    /**
     * 得到屏幕高度
     * 
     * @return
     */
//    @SuppressWarnings("deprecation")
//    public static int getScreenHeight() {
//        return ((WindowManager) BaseApplication.getInstance().getSystemService(Context.WINDOW_SERVICE))
//                .getDefaultDisplay().getHeight();
//    }

    @SuppressWarnings("deprecation")
    public static int getScreenHeight(Context context) {
        return ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE))
            .getDefaultDisplay().getHeight();
    }

//    public static int getMinScreen() {
//        int width = getScreenWidth();
//        int height = getScreenHeight();
//        return Math.min(width, height);
//    }

    /**
     * 将一倍尺寸缩放到当前屏幕大小的尺寸（宽）
     * 
     * @param w
     * @return
     */
//    public static int zoomWidth(int w) {
//        int sw = 0;
//        sw = Math.min(getScreenWidth(), getScreenHeight());
//
//        return Math.round(w * sw / 320f + 0.5f);
//    }

    public static int zoomWidth(Context context,int w) {
        int sw = 0;
        sw = Math.min(getScreenWidth(context), getScreenHeight(context));

        return Math.round(w * sw / 320f + 0.5f);
    }

    /**
     * 将一倍尺寸缩放到当前屏幕大小的尺寸（高）
     * 
     * @param h
     * @return
     */
//    public static int zoomHeight(int h) {
//        int sh = 0;
//        sh = getScreenHeight();
//
//        return (int) (h * sh / 480f + 0.5f);
//    }

    /**
     * 缩放控件
     * 
     * @param w
     * @param view
     */
//    public static void zoomViewWidth(int w, View view) {
//        if (view == null) {
//            return;
//        }
//
//        LayoutParams params = view.getLayoutParams();
//        if (params == null) {
//            return;
//        }
//
//        int width = zoomWidth(w);
//        params.width = width;
//    }

    /**
     * 缩放控件
     * 
     * @param w
     * @param h
     * @param view
     */
//    public static void zoomView(int w, int h, View view) {
//        if (view == null) {
//            return;
//        }
//
//        LayoutParams params = view.getLayoutParams();
//
//        if (params == null) {
//            return;
//        }
//
//        params.width = zoomWidth(w);
//        params.height = zoomWidth(h);
//    }

    public static void zoomView(Context context,int w, int h, View view) {
        if (view == null) {
            return;
        }

        LayoutParams params = view.getLayoutParams();

        if (params == null) {
            return;
        }

        params.width = zoomWidth(context,w);
        params.height = zoomWidth(context,h);
    }

    /**
     * 缩放控件
     * 
     * @param view
     */
//    public static void zoomViewFull(View view) {
//        if (view == null) {
//            return;
//        }
//
//        LayoutParams params = view.getLayoutParams();
//
//        params.width = Math.max(getScreenWidth(), BaseApplication.sRawHeight);
//        params.height = BaseApplication.sWidth;
//        // 强制刷新一下
//        if (BaseApplication.sRawHeight != BaseApplication.sHeight) {
//            view.invalidate();
//        }
//    }

    public static void zoomViewFull(Context context,View view) {
        if (view == null) {
            return;
        }

        LayoutParams params = view.getLayoutParams();

        params.width = Math.max(getScreenWidth(context), LetvSDKUtils.sRawHeight);
        params.height = LetvSDKUtils.sWidth;
        // 强制刷新一下
        if (LetvSDKUtils.sRawHeight != LetvSDKUtils.sHeight) {
            view.invalidate();
        }
    }

    /**
     * 获取顶部状态栏高度
     * 
     * @param act
     * @return
     */
    public static int getStatusBarHeight(Activity act) {
        Rect frame = new Rect();
        act.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
        return frame.top;
    }

    /**
     * 判断是否是横屏
     * 
     * @param activity
     * @return
     */
    public static boolean isLandscape(Context activity) {
        if (activity == null) {
            return false;
        }

        int t = activity.getResources().getConfiguration().orientation;
        return t == Configuration.ORIENTATION_LANDSCAPE;

    }

    /**
     * 全屏
     * 
     * @param activity
     */
    public static void fullScreen(Activity activity) {
        activity.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN);
    }

    /**
     * 取消全屏
     * 
     * @param activity
     */
    public static void cancelFullScreen(Activity activity) {
        activity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
    }

    /**
     * 设置为横屏
     * 
     * @param activity
     */
    public static void setScreenLandscape(Activity activity) {
        activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
    }

    /**
     * 设置为竖屏
     * 
     * @param activity
     */
    public static void setScreenPortrait(Activity activity) {
        activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    }

    /**
     * dip转px
     * 
     * @param dipValue
     * @return
     */
//    public static int dipToPx(int dipValue) {
//        final float scale = BaseApplication.getInstance().getResources().getDisplayMetrics().density;
//        int pxValue = (int) (dipValue * scale + 0.5f);
//
//        return pxValue;
//    }

    /**
     * dip转px
     *
     * @param dipValue
     * @return
     */
    public static int dipToPx(Context context,int dipValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        int pxValue = (int) (dipValue * scale + 0.5f);

        return pxValue;
    }

    /**
     * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
     * 
     * @param context
     * @param pxValue
     * @return
     */
//    public static int px2dip(Context context, float pxValue) {
//        final float scale = BaseApplication.getInstance().getResources().getDisplayMetrics().density;
//        return (int) (pxValue / scale + 0.5f);
//    }

    /**
     * 打开屏幕常亮
     */
    public static void enableScreenAlwaysOn(Context context) {
        if (context instanceof Activity) {
            ((Activity) context).getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        }
    }

    /**
     * 关闭屏幕常亮
     */
    public static void disableScreenAlwaysOn(Context context) {
        if (context instanceof Activity) {
            // 由于会引起栈溢出，暂时取消
            // ((Activity)context).getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        }
    }

    /**
     * 测量view大小
     * 
     * @param child
     */
    public static void measureView(View child) {
        ViewGroup.LayoutParams p = child.getLayoutParams();
        if (p == null) {
            p = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        }
        int childWidthSpec = ViewGroup.getChildMeasureSpec(0, 0 + 0, p.width);
        int lpHeight = p.height;
        int childHeightSpec;
        if (lpHeight > 0) {
            childHeightSpec = MeasureSpec.makeMeasureSpec(lpHeight, MeasureSpec.EXACTLY);
        } else {
            childHeightSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
        }
        child.measure(childWidthSpec, childHeightSpec);
    }

    /**
     * 测量该控件的 尺寸
     * 
     * @param v
     * @return int[]{width,height}
     */
    public static int[] measure(View v) {
        v.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
                View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
        return new int[] { v.getMeasuredWidth(), v.getMeasuredHeight() };
    }

    /**
     * 缩放控件
     * */
//    public static void zoomViewHeight(int h, View view) {
//        if (view == null) {
//            return;
//        }
//
//        LayoutParams params = view.getLayoutParams();
//
//        if (params == null) {
//            return;
//        }
//
//        params.height = zoomWidth(h);
//    }

    /**
     * 源代码中dialog的一个方法，但是感觉有点傻，留着以后优化一下，先用
     * 
     * @param activity
     * @param message
     * @param yes
     */
    public static void call(Activity activity, String message, DialogInterface.OnClickListener yes) {
        if (activity == null) {
            return;
        }

        Dialog dialog = new AlertDialog.Builder(activity).setTitle(R.string.dialog_default_title)
                .setIcon(R.drawable.letv_dialog_icon).setMessage(message).setPositiveButton(R.string.dialog_default_ok, yes)
                .create();

        if (!activity.isFinishing() && !activity.isRestricted()) {
            dialog.show();
        }
    }

    /**
     * public static void showToast(int txtId) { mToast =
     * Toast.makeText(LetvApplication.getInstance(), txtId, Toast.LENGTH_SHORT);
     * mToast.setText(txtId); mToast.setGravity(Gravity.CENTER, 0, 0);
     * mToast.setDuration(Toast.LENGTH_SHORT); mToast.show(); }
     * 
     * /** 隐藏键盘输入法
     * 
     * @param mActivity
     */
    public static void hideInputMethod(Activity mActivity) {
        if (null != mActivity && null != mActivity.getCurrentFocus()) {
            InputMethodManager mInputMethodManager = (InputMethodManager) mActivity
                    .getSystemService(Context.INPUT_METHOD_SERVICE);
            if (null != mInputMethodManager) {
                mInputMethodManager.hideSoftInputFromWindow(mActivity.getCurrentFocus().getWindowToken(),
                        InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }
    }


    /**
     * 测量该控件的 尺寸
     * 
     * @param v
     * @return int[]{width,height}
     */
    public static int[] measureSize(View v) {
        int w = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        int h = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        v.measure(w, h);
        int width = v.getMeasuredWidth();
        int height = v.getMeasuredHeight();
        return new int[] { width, height };
    }

    /**
     * 将一倍尺寸缩放到当前屏幕大小的尺寸（高）
     * */
//    public static int zoomRealHeight(int h) {
//        int sh = 0;
//        sh = Math.max(getScreenWidth(), getScreenHeight());
//
//        return (int) (h * sh / 480f + 0.5f);
//    }

    /**
     * 获取窗口播放模式中播放窗口的宽度
     * 
     * @return
     */
    public static int getDisplayWidth() {
        // DisplayMetrics dm = context.getResources().getDisplayMetrics();
        int w = LetvConstant.Global.displayMetrics.widthPixels;// dm.widthPixels;
        int h = LetvConstant.Global.displayMetrics.heightPixels;// dm.heightPixels;
        return w < h ? w : h;
    }

    @SuppressWarnings("deprecation")
    public static boolean isScreenOn(Context context) {
        PowerManager manager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
        return manager.isScreenOn();
    }

    public static void callDialogMsgPosNeg(Activity activity, String msgId, int yes, int no,
            DialogInterface.OnClickListener yesListener, DialogInterface.OnClickListener noListener) {
        TipBean dialogMsgByMsg = TipUtils.getTipBean(activity,msgId);

        if (activity == null || dialogMsgByMsg == null) {
            return;
        }

        Dialog dialog = new AlertDialog.Builder(activity)
                .setTitle(
                        (!"".equals(dialogMsgByMsg.getTitle()) && dialogMsgByMsg.getTitle() != null) ? dialogMsgByMsg
                                .getTitle() : activity.getString(R.string.dialog_default_title))
                .setIcon(R.drawable.letv_dialog_icon).setMessage(dialogMsgByMsg.getMessage()).setCancelable(false)
                .setPositiveButton(yes, yesListener).setNegativeButton(no, noListener).create();

        if (!activity.isFinishing() && !activity.isRestricted()) {
            dialog.show();
        }
    }
}
